//
//  oAuthViewController.swift
//  weibo
//
//  Created by HJ on 16/3/16.
//  Copyright © 2016年 HJ. All rights reserved.
//

import UIKit
import AFNetworking

class oAuthViewController: UIViewController,UIWebViewDelegate {

    var webView = UIWebView()
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        
        view.backgroundColor = UIColor.whiteColor()
        setNav()
        loadWeb()
        // Do any additional setup after loading the view.
    }
    
    private func setNav() {
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "dismissOAthVC")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "addTestAccount")
    }
    
    private func loadWeb() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

    @objc private func addTestAccount() {
        let jsString = "document.getElementById('userId').value = '641669093@qq.com', document.getElementById('passwd').value = '19911221NWJNXHGX' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    @objc private func dismissOAthVC() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        

        if (request.URL?.absoluteString ?? "").containsString("code=") {
            let codeStr = request.URL!.query!
            let code = (codeStr as NSString).substringFromIndex(5)
            print(code)
            return false
        }
        
        
        return true
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
